﻿using FluentValidation;
using Microsoft.AspNetCore.Mvc;

namespace Customers.Api.Middlewares;

public class ValidationExceptionMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<ValidationExceptionMiddleware> _logger;

    public ValidationExceptionMiddleware(RequestDelegate next, ILogger<ValidationExceptionMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception exception)
        {
            var error = new ValidationProblemDetails
            {
                Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1",
                Extensions =
                {
                    ["traceId"] = context.TraceIdentifier
                }
            };

            if (exception is ValidationException validationException)
            {
                _logger.LogError("发生了异常：{Message} {@Errors} {@Exception}", validationException.Message, validationException.Errors, validationException);
                error.Status = StatusCodes.Status400BadRequest;
                foreach (var validationFailure in validationException.Errors)
                {
                    error.Errors.Add(new KeyValuePair<string, string[]>(
                        validationFailure.PropertyName,
                        new[] { validationFailure.ErrorMessage }));
                }
            }
            else
            {
                _logger.LogError("发生了异常：{Message}", exception.Message);
                error.Status = StatusCodes.Status500InternalServerError;
            }


            context.Response.StatusCode = error.Status!.Value;

            await context.Response.WriteAsJsonAsync(error);
        }
    }
}